"use client";
import React, { useEffect, useState, useCallback } from "react";
import {
  Button,
  Col,
  Form,
  Input,
  Row,
  Table,
  Modal,
  Switch,
  Select,
  Card,
  Space,
  Popconfirm,
  InputNumber,
  Tabs,
  Tooltip,
  App,
} from "antd";
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  SettingOutlined,
  SecurityScanOutlined,
  MailOutlined,
  CloudServerOutlined,
  AppstoreOutlined,
  BulbOutlined,
} from "@ant-design/icons";
import { Pagination } from "@/utils/db/dbTools";
import {
  sysSettingTableColumns,
  configTypeOptions,
  formRules,
  defaultConfigTemplates,
} from "./tools";
import { system } from "@/forent-api/api";

const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

interface SettingData {
  id?: number;
  config_key: string;
  config_value: string;
  config_name: string;
  config_type: string;
  description?: string;
  is_encrypted: number;
  sort_order: number;
}

const SystemSettingContent: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<SettingData[]>([]);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
  });

  // 搜索表单
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<any>({});

  // 编辑弹窗
  const [modalVisible, setModalVisible] = useState(false);
  const [modalType, setModalType] = useState<"add" | "edit">("add");
  const [currentRecord, setCurrentRecord] = useState<SettingData | null>(null);
  const [editForm] = Form.useForm();

  // 批量设置弹窗
  const [batchModalVisible, setBatchModalVisible] = useState(false);
  const [batchSettings, setBatchSettings] = useState<SettingData[]>([]);

  // 配置类型选项
  const [typeOptions, setTypeOptions] = useState(configTypeOptions);

  // 当前选中的配置类型 tab
  const [activeConfigType, setActiveConfigType] = useState("all");

  const { message, modal } = App.useApp();

  // 获取配置列表
  const fetchData = useCallback(
    async (overrideParams?: any) => {
      setLoading(true);
      try {
        const queryParams = {
          page: overrideParams?.page || pagination.current,
          pageSize: overrideParams?.pageSize || pagination.pageSize,
          ...searchParams,
          ...overrideParams,
        };

        const currentConfigType =
          overrideParams?.config_type || activeConfigType;
        if (currentConfigType !== "all") {
          queryParams.config_type = currentConfigType;
        }

        const response = await system.getSettingList(queryParams);
        if (response.code === 200) {
          setData(response.data.list || []);
          setTotal(response.data.pagination?.total || 0);
        } else {
          message.error(response.msg || "获取配置列表失败");
        }
      } catch (error) {
        message.error("获取配置列表失败");
      } finally {
        setLoading(false);
      }
    },
    [pagination.current, pagination.pageSize, searchParams, activeConfigType]
  );

  // 搜索
  const handleSearch = (values: any) => {
    setSearchParams(values);
    setPagination({ ...pagination, current: 1 });
    fetchData({ ...values, page: 1 });
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination({ ...pagination, current: 1 });
    fetchData({ page: 1 });
  };

  // 打开编辑弹窗
  const handleEdit = (type: "add" | "edit", record?: SettingData) => {
    setModalType(type);
    setCurrentRecord(record || null);
    setModalVisible(true);

    if (type === "edit" && record) {
      editForm.setFieldsValue({
        ...record,
        config_value: record.is_encrypted === 1 ? "" : record.config_value,
      });
    } else {
      editForm.resetFields();
      // 设置默认值
      editForm.setFieldsValue({
        config_type: activeConfigType !== "all" ? activeConfigType : "",
        is_encrypted: 0,
        sort_order: 0,
      });
    }
  };

  // 保存配置
  const handleSave = async (values: SettingData) => {
    try {
      setLoading(true);
      let response;

      if (modalType === "add") {
        response = await system.addSetting(values);
      } else {
        response = await system.updateSetting({
          ...values,
          id: currentRecord?.id,
        });
      }

      if (response.code === 200) {
        message.success(modalType === "add" ? "新增配置成功" : "更新配置成功");
        setModalVisible(false);
        fetchData();
      } else {
        message.error(response.msg || "操作失败");
      }
    } catch (error) {
      message.error("操作失败");
    } finally {
      setLoading(false);
    }
  };

  // 删除配置
  const handleDelete = async (record: SettingData) => {
    try {
      setLoading(true);
      const response = await system.deleteSetting({ ids: [record.id] });
      if (response.code === 200) {
        fetchData();
      } 
    } catch (error) {
      message.error("删除失败");
    } finally {
      setLoading(false);
    }
  };

  // 初始化默认配置
  const initDefaultConfigs = async (configType: string) => {
    const templates =
      defaultConfigTemplates[configType as keyof typeof defaultConfigTemplates];
    if (!templates) {
      message.warning("暂无该类型的默认配置模板");
      return;
    }

    try {
      setLoading(true);
      const configsToCreate = templates.map(
        (config: any) => ({
          ...config,
          config_type: configType,
        })
      );
      const response = await system.batchUpdateSettings({
        configs: configsToCreate,
      });
      if (response.code === 200) {
        message.success(`初始化[${configType}]默认配置成功`);
        fetchData({ config_type: configType });
      } 
    } catch (error) {
      message.error("初始化配置失败");
    } finally {
      setLoading(false);
    }
  };

  // 表格列配置
  const columns = sysSettingTableColumns(handleEdit, handleDelete);

  // 数据获取的核心useEffect
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  // 配置类型变化时重置分页
  useEffect(() => {
    // 使用函数式更新避免依赖pagination对象，防止循环
    setPagination((prev) => ({ ...prev, current: 1 }));
  }, [activeConfigType]);

  // Tab配置
  const tabItems = [
    {
      key: "all",
      label: (
        <span>
          <AppstoreOutlined />
          全部配置
        </span>
      ),
    },
    {
      key: "system_basic",
      label: (
        <span>
          <SettingOutlined />
          系统基础
        </span>
      ),
    },
    {
      key: "security",
      label: (
        <span>
          <SecurityScanOutlined />
          安全配置
        </span>
      ),
    },
    {
      key: "email",
      label: (
        <span>
          <MailOutlined />
          邮件配置
        </span>
      ),
    },
    {
      key: "file_storage",
      label: (
        <span>
          <CloudServerOutlined />
          文件存储
        </span>
      ),
    },
    {
      key: "ui",
      label: (
        <span>
          <BulbOutlined />
          界面配置
        </span>
      ),
    },
  ];

  return (
    <div className="h-full flex flex-col">
      {/* 搜索区域 */}
      <Card className="mb-2" size="small">
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          className="flex flex-wrap gap-4"
        >
          <Form.Item name="config_key" label="配置键">
            <Input placeholder="请输入配置键" allowClear />
          </Form.Item>
          <Form.Item name="config_name" label="配置名称">
            <Input placeholder="请输入配置名称" allowClear />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
                loading={loading}
              >
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      {/* 配置类型标签页 */}
      <Card className="flex-1 flex flex-col" size="small">
        <Tabs
          activeKey={activeConfigType}
          onChange={setActiveConfigType}
          tabBarExtraContent={
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleEdit("add")}
              >
                新增配置
              </Button>
              {activeConfigType !== "all" && (
                <Tooltip title="初始化该类型的默认配置">
                  <Button
                    onClick={() => initDefaultConfigs(activeConfigType)}
                    loading={loading}
                  >
                    初始化默认配置
                  </Button>
                </Tooltip>
              )}
            </Space>
          }
          items={tabItems}
        />

        {/* 表格 */}
        <div className="flex-1  ">
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            loading={loading}
            size="small"
            scroll={{ y: "calc(100vh - 316px)" }}
            pagination={{
              position: ["bottomCenter"],
              current: pagination.current,
              pageSize: pagination.pageSize,
              total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              onChange: (page, pageSize) => {
                setPagination({ current: page, pageSize: pageSize || 10 });
              },
            }}
          />
        </div>
      </Card>

      {/* 编辑弹窗 */}
      <Modal
        title={modalType === "add" ? "新增配置" : "编辑配置"}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        width={600}
        footer={null}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleSave}
          className="mt-4"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="config_key"
                label="配置键"
                rules={formRules.config_key}
              >
                <Input
                  placeholder="请输入配置键"
                  disabled={modalType === "edit"}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="config_name"
                label="配置名称"
                rules={formRules.config_name}
              >
                <Input placeholder="请输入配置名称" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="config_type"
                label="配置类型"
                rules={formRules.config_type}
              >
                <Select placeholder="请选择配置类型">
                  {configTypeOptions.map((option) => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="is_encrypted"
                label="是否加密"
                valuePropName="checked"
              >
                <Switch checkedChildren="加密" unCheckedChildren="明文" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="sort_order"
                label="排序"
                rules={formRules.sort_order}
              >
                <InputNumber
                  min={0}
                  max={9999}
                  placeholder="排序"
                  style={{ width: "100%" }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="config_value"
            label="配置值"
            rules={formRules.config_value}
          >
            <TextArea
              rows={3}
              placeholder={
                modalType === "edit" && currentRecord?.is_encrypted === 1
                  ? "加密配置项，留空表示不修改"
                  : "请输入配置值"
              }
            />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={formRules.description}
          >
            <TextArea rows={2} placeholder="请输入配置描述" />
          </Form.Item>

          <Form.Item className="text-right mb-0">
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

// 系统设置主组件
export default function SystemSetting() {
  return (
    <div className="h-full  rounded-[10px] px-2">
      <SystemSettingContent />
    </div>
  );
}
